<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="title"
    :destroy-on-close="true"
    draggable
    :align-center="true"
    style="min-width: 1700px; height: 800px; overflow: auto"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      style="width: 100%"
    >
      <div class="production-version-product-info">
        <h4 style="margin-top: 0">生产版本</h4>
        <el-row>
          <el-col :span="6">
            <el-form-item label="成品物料号" prop="materialId">
              <el-input
                v-model="formData.materialCode"
                placeholder="请选择成品物料号"
                clearable
                readonly
                style="width: 100%"
                @click="showWorkOrderSelect"
              >
                <template #append>
                  <el-button type="success" plain @click="showWorkOrderSelect"
                    >选择</el-button
                  >
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产版本编号" prop="versionNo">
              <el-input
                v-model="formData.versionNo"
                placeholder="请输入生产版本编号"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="成品BOM" prop="bomId">
              <el-select
                style="width: 100%"
                v-model="formData.bomId"
                placeholder="请选择成品BOM"
                @change="changeBom"
                clearable
              >
                <el-option
                  v-for="item in bomList"
                  :key="item.id"
                  :label="item.bomCode"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产节拍" prop="tactTime">
              <el-input
                v-model="formData.tactTime"
                placeholder="请输入生产节拍"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div>
              <p style="margin-left: 2px; color: #969696">瓶颈工序的生产节拍</p>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产版本描述" prop="remarks">
              <el-input
                v-model="formData.remarks"
                placeholder="请输入生产版本描述"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="启用状态" prop="tactTime">
              <el-radio-group v-model="formData.enabled">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="production-version-product-info">
        <h4 style="margin-top: 0">工艺信息</h4>
        <div class="mb-[10px]">
          <el-button type="success" @click="addRow"
            ><i-ep-plus />新增行</el-button
          >
          <el-button type="success" @click="insertRow"
            ><i-ep-plus />插入行</el-button
          >
        </div>
        <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="formData.details"
          highlight-current-row
          class="produce-version-table"
          border
          :cell-style="{ 'text-align': 'center' }"
          @row-click="selectRow"
          style="height: 330px"
        >
          <el-table-column
            label="加工顺序"
            align="center"
            prop="workSequence"
            min-width="120"
          >
            <template #default="scope">
              <el-form-item
                label-width="1"
                :prop="'details.' + scope.$index + '.workSequence'"
                :rules="rules.workSequence"
              >
                <el-input-number
                  v-model="scope.row.workSequence"
                  :controls="false"
                  style="width: 100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="工序号"
            align="center"
            prop="processId"
            min-width="150"
          >
            <template #default="scope">
              <el-form-item
                label-width="1"
                :prop="'details.' + scope.$index + '.processId'"
                :rules="rules.processId"
              >
                <el-select
                  v-model="scope.row.processId"
                  placeholder="请选择工序"
                  clearable
                  @change="changeProcess(scope.row)"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in processList"
                    :key="item.id"
                    :label="`${item.processCode}-${item.processName}`"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="工作中心"
            align="center"
            prop="workCenterCode"
            min-width="150"
          >
            <template #default="scope">
              <el-form-item label-width="1" class="equip-form-item">
                {{ scope.row.workCenterCode }}
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="最小批量"
            align="center"
            prop="minLot"
            width="120"
          >
            <template #default="scope">
              <el-form-item
                label-width="1"
                :prop="'details.' + scope.$index + '.minLot'"
                :rules="rules.minLot"
              >
                <el-input-number
                  v-model="scope.row.minLot"
                  :controls="false"
                  style="width: 100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="小时产能"
            align="center"
            prop="hourlyCapacity"
            min-width="140"
          >
            <template #default="scope">
              <el-form-item
                label-width="1"
                :prop="'details.' + scope.$index + '.hourlyCapacity'"
                :rules="rules.hourlyCapacity"
              >
                <el-input-number
                  v-model="scope.row.hourlyCapacity"
                  style="width: 100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="基础产出数量"
            align="center"
            prop="baseQuantity"
            min-width="140"
          >
            <template #default="scope">
              <el-form-item
                label-width="1"
                :prop="'details.' + scope.$index + '.baseQuantity'"
                :rules="rules.baseQuantity"
              >
                <el-input-number
                  v-model="scope.row.baseQuantity"
                  style="width: 100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="数量单位"
            align="center"
            prop="baseQuantityUnit"
            min-width="120"
          >
            <template #default="scope">
              <el-form-item
                label-width="1"
                :prop="'details.' + scope.$index + '.baseQuantityUnit'"
                :rules="rules.baseQuantityUnit"
              >
                <el-select
                  v-model="scope.row.baseQuantityUnit"
                  placeholder="数量单位"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in useDictionary('MeasurementUnit')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="生产节拍"
            align="center"
            prop="tactTime"
            min-width="120"
          >
            <template #default="scope">
              <el-form-item
                label-width="1"
                :prop="'details.' + scope.$index + '.tactTime'"
                :rules="rules.tableTactTime"
              >
                <el-input-number
                  v-model="scope.row.tactTime"
                  :controls="false"
                  style="width: 100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="加工人数"
            align="center"
            prop="workerQuantity"
            min-width="120"
          >
            <template #default="scope">
              <el-form-item
                label-width="1"
                :prop="'details.' + scope.$index + '.workerQuantity'"
                :rules="rules.workerQuantity"
              >
                <el-input-number
                  v-model="scope.row.workerQuantity"
                  :controls="false"
                  style="width: 100%"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="是否报工"
            align="center"
            prop="isBackflush"
            min-width="90"
          >
            <template #default="scope">
              <el-form-item label-width="1" class="equip-form-item">
                <el-switch
                  v-model="scope.row.isBackflush"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            label="是否外协"
            align="center"
            prop="isOutsourcing"
            min-width="90"
          >
            <template #default="scope">
              <el-form-item label-width="1" class="equip-form-item">
                <el-switch
                  v-model="scope.row.isOutsourcing"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            prop="action"
            min-width="290"
          >
            <template #default="scope">
              <el-form-item label-width="1" class="equip-form-item">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogEvent(event.worker, scope.row)"
                >
                  人数设置
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogEvent(event.equip, scope.row)"
                >
                  设备
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogEvent(event.material, scope.row)"
                >
                  物料
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogEvent(event.supplier, scope.row)"
                >
                  外协供应商
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="removeRow(scope.row)"
                >
                  删除
                </el-button>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="save"
          >保存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <material-select
    :visible="selectDialogSELECT.visible"
    @change-visible="changeVisibleSELECT"
    :plantId="formData.plantId"
    :brekList="brekList"
  />
  <worker-dialog />
  <equip-dialog />
  <mat-dialog />
  <supplier-dialog />
</template>
<script setup lang="ts">
import useEvent from "@/utils/useEvent";
import { productionVersionHook } from "@/views/mes/produceVersion/hook/productionVersionHook";
import request from "@/utils/request";
import { useDictionary } from "@/utils/useTable";

const { eventBusEmit, eventBusOn } = useEvent();
const { event, api, validateInt, validateDecimal } = productionVersionHook();
defineOptions({
  name: "PRODUCTIONVERSIONPRODUCTIONVERSIONEDIT",
  inheritAttrs: false,
});
const visibleDialog = ref(false);

const loading = ref(false);

const title = ref("");

const formRef = ref(null);

const closeDialog = () => {
  visibleDialog.value = false;
  resetForm();
};

const openEditOrCopy = async (data) => {
  visibleDialog.value = true;
  Object.assign(formData, data);
  await getProcessList();
  formData.details?.forEach((item) => {
    changeProcess(item);
  });
  await getBomList();
};

onMounted(() => {
  eventBusOn(
    event.editByTemplateEvent,
    ({ plantId, plantCode, processTemplate }) => {
      resetForm();
      title.value = "参考工艺路线模版创建";
      visibleDialog.value = true;
      formData.plantId = plantId;
      formData.plantCode = plantCode;
      getTemplateDetail(processTemplate);
      getProcessList();
    }
  );
  eventBusOn(event.editEvent, (data) => {
    title.value = "编辑";
    resetForm();
    openEditOrCopy(data);
  });
  eventBusOn(event.copyEvent, (data) => {
    title.value = "复制";
    resetForm();
    openEditOrCopy(data);
  });
});

const getTemplateDetail = async (id) => {
  const { data } = await request({
    url: api.getTemplateDetail,
    method: "post",
    data: { id },
  });
  data?.forEach((item) => (item.id = null));
  formData.details = data;
  formData.details?.forEach((item) => {
    changeProcess(item);
  });
};

const formData = reactive({
  plantId: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  versionNo: "",
  bomId: "",
  bomCode: "",
  tactTime: "",
  organizationId: "",
  ids: [],
  isDefault: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  remarks: "",
  version: "",
  baseQuantityUnit: "",
  enabled: 1,
  deleted: 0,
  details: [],
});

const resetForm = () => {
  formData.id = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.versionNo = "";
  formData.bomId = "";
  formData.bomCode = "";
  formData.tactTime = "";
  formData.organizationId = "";
  formData.ids = [];
  formData.isDefault = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.version = "";
  formData.enabled = 1;
  formData.deleted = 0;
  formData.baseQuantityUnit = "";
  formData.details = [];
};

const selectedRow = ref();

const selectRow = (val) => {
  selectedRow.value = formData.details.indexOf(val);
};

const removeRow = (row) => {
  const indexOf = formData.details.indexOf(row);
  formData.details.splice(indexOf, 1);
  formRef.value.validate();
};

const insertRow = () => {
  if (selectedRow.value !== -1) {
    formRef.value.validate();
    formData.details.splice(selectedRow.value, 0, {
      workSequence: "",
      processId: "",
      processCode: "",
      workCenterId: "",
      workCenterCode: "",
      minLot: 0,
      hourlyCapacity: 0,
      baseQuantity: 0,
      baseQuantityUnit: "",
      tactTime: 0,
      workerQuantity: 0,
      isBackflush: 0,
      isOutsourcing: 0,
      listWorker: [],
      listEquipment: [],
      listMat: [],
      listSupplier: [],
    });
  }
};

const addRow = () => {
  formData.details.push({
    workSequence: "",
    processId: "",
    processCode: "",
    workCenterId: "",
    workCenterCode: "",
    minLot: 0,
    hourlyCapacity: 0,
    baseQuantity: 0,
    baseQuantityUnit: "",
    tactTime: 0,
    workerQuantity: 0,
    isBackflush: 0,
    isOutsourcing: 0,
    listWorker: [],
    listEquipment: [],
    listMat: [],
    listSupplier: [],
  });
};

const changeProcess = (row) => {
  const find = processList.value.find((item) => item.id === row.processId);
  row.processCode = find?.processCode;
  row.processName = find?.processName;
  row.workCenterCode = find?.workCenterCode;
  row.workCenterId = find?.workCenterId;
};

const processList = ref([]);

const getProcessList = async () => {
  const { data } = await request({
    url: api.getProcessList,
    method: "post",
    data: {},
  });
  processList.value = data;
};

const bomList = ref([]);

const getBomList = async () => {
  const { data } = await request({
    url: api.getBom,
    method: "post",
    data: {
      materialId: formData.materialId,
    },
  });
  bomList.value = data;
};

//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    formData.materialId = data.id;
    formData.materialName = data.materialName;
    formData.materialCode = data.materialCode;
    formData.baseQuantityUnit = data.unit;
    getBomList();
    formData.bomId = "";
  }
};
// 回显的数据
const brekList = ref([]);
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};

const openDialogEvent = (event, row) => {
  eventBusEmit(event, row);
};

const changeBom = (bomId) => {
  formData.bomCode = "";
  const find = bomList.value.find((item) => item.id === bomId);
  formData.bomCode = find?.bomCode;
};

const save = async () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (!formData.details || formData.details.length <= 0) {
        ElMessage.error("请添加工艺信息");
        return;
      }
      const haveNoMatBackFlush = formData.details
        .filter((item) => item.isBackflush)
        .filter(
          (item) =>
            !item.listMat ||
            item.listMat.length <= 0 ||
            !item.listMat.some((item) => item.materialRole === 1)
        )
        .map((item) => item.workSequence);
      if (haveNoMatBackFlush.length > 0) {
        ElMessage.error(
          `报工工序加工顺序:${haveNoMatBackFlush.join(",")}加工物料不能为空`
        );
        return;
      }
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: api.save,
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      eventBusEmit(event.refreshEvent);
    }
  });
};
/** rules规则 */
const rules = reactive({
  materialId: [
    {
      required: true,
      message: "请选择成品物料号",
      trigger: ["blur", "change"],
    },
  ],
  versionNo: [
    {
      required: true,
      message: "请输入生产版本编号",
      trigger: ["blur", "change"],
    },
    {
      max: 50,
      message: "最多可输入50个字符",
      trigger: ["blur", "change"],
    },
  ],
  bomId: [
    {
      required: true,
      message: "请选择成品BOM",
      trigger: ["blur", "change"],
    },
  ],
  tactTime: [
    {
      validator: validateDecimal,
      trigger: ["blur", "change"],
    },
  ],
  remarks: [
    {
      max: 255,
      message: "最多可输入255个字符",
      trigger: ["blur", "change"],
    },
  ],
  workSequence: [
    {
      required: true,
      message: "请输入加工顺序",
      trigger: ["blur", "change"],
    },
    {
      validator: validateInt,
      trigger: ["blur", "change"],
    },
  ],
  processId: [
    {
      required: true,
      message: "请选择工序",
      trigger: ["blur", "change"],
    },
  ],
  minLot: [
    {
      required: true,
      message: "请输入最小批量",
      trigger: ["blur", "change"],
    },
    {
      validator: validateDecimal,
      trigger: ["blur", "change"],
    },
  ],
  hourlyCapacity: [
    {
      required: true,
      message: "请输入小时产能",
      trigger: ["blur", "change"],
    },
    {
      validator: validateDecimal,
      trigger: ["blur", "change"],
    },
  ],
  baseQuantity: [
    {
      required: true,
      message: "请输入基础产出数量",
      trigger: ["blur", "change"],
    },
    {
      validator: validateDecimal,
      trigger: ["blur", "change"],
    },
  ],
  baseQuantityUnit: [
    {
      required: true,
      message: "请选择数量单位",
      trigger: ["blur", "change"],
    },
  ],
  tableTactTime: [
    {
      required: true,
      message: "请输入生产节拍",
      trigger: ["blur", "change"],
    },
    {
      validator: validateDecimal,
      trigger: ["blur", "change"],
    },
  ],
  workerQuantity: [
    {
      required: true,
      message: "请输入加工人数",
      trigger: ["blur", "change"],
    },
    {
      validator: validateInt,
      trigger: ["blur", "change"],
    },
  ],
});
</script>
<style scoped>
::v-deep .el-table__body tr.current-row > td.el-table__cell {
  //background-color: var(--el-table-current-row-bg-color);
  //background-color: #a6def5 !important;
}
</style>
